// pages/common/productDetail/productDetail.js
import regeneratorRuntime from '../../../utils/runtime.js';
import {img_list,jsonParamToQueryStr} from '../../../utils/util.js';
import { SpecVertex } from '../../../utils/SpecVertex'
import { getData, setData, clearData, dataKey } from '../../../utils/storage.js';
import shareFun from '../../../utils/shareFun.js';
import {
  saveVisit,
  search,
  convert,
  proInfo,
  proDetail,
  getBarrage,
  collect,
  login,
  getUserData,
  recordGrowth,
  goods_shareimg_post,
  shareBind,
  getuid_byopenid,
  upload_starx_singletmp,
  goodsDetail,
  text2qr,
  get_near_spreader,
  mini_img,
  getBanner,
  goods_item_save
} from '../../../utils/imapi.js';

var log = require('../../../utils/log.js') // 引用上面的log.js文件
var app = getApp()
var down_num = 0, setT1, setT2, setT3;


Page({

  /**
   * 页面的初始数据
   */
  data: {
	  flex_center:false, //购买星品劵的样式
	  In:true,
    show_part: false,
    part_count: 1,  //商品数量
	part_count1: 1, //星品劵的数量
    coupon_tpwd: '', //暂不用了 使用zhuan_url
    show_buy_active: false,
    show_buy: false,
    show_load: false,
    tabIndex1: 0,
    sliderLeft: 113,
    sliderOffset: 240,
    sliderLeft1: 170,
    sliderOffset1: 375,
    menuFixed: false,
    image_box_top: 0,
    image_box_height: 0,
    is_load: false,
	pop:false,
    tabs: [
      { "id": 1, "name": "详情", "p": "", "is_selected": 1 },
      { "id": 2, "name": "推荐", "p": "JD", "is_selected": 0 },
    ],
    tabIndex: 0,
    cur_btn_index: 0,
    new_arr: [], // 商品多图多图 展示
    downImg: '/images/sale/down_img.png',
    btnArr: [
      { img: '/images/index/share_btn_icon1.png', text: '分享到微信', name: '小程序卡片', bind: '' },
      { img: '/images/index/share_btn_icon2.png', text: '保存海报(朋友圈)', name: '商品海报', bind: 'downloadImg' },
      { img: '/images/index/share_btn_icon3.png', text: '保存选中图片', name: '商品多图', bind: 'downImg' },
    ],
    share: {
      img: '/images/index/detail_test.png',
      title: '百草味 酵母软面包800g/箱 整箱手撕 面包营养早餐休闲食品零食小吃饼阿斯达我打算大武大厦打完'
    },
    buy_index: -1,
    buy_list: [],
    show_share_xp: false,
    show_share: 0,
    show_poster: 0,
    is_show_detail: 1,
    currentIndicator: 1,
    show_title: true,
    heigth: app.globalData.CustomBar,
    is_iphoneX: app.globalData.isIphonex,
    bar_top: app.globalData.CustomBar,
    small_y: app.globalData.screenWidth,
    productList: [], // 产品 推荐
    show: 0,
    is_show_big: 0,
    is_show_big1: 0,
    show_go: false,
    show_go_top: false,
    tuiguang_txt: "",
    p_obj: {
      'PDD': '拼多多',
      'TB': '淘宝',
      'JD': '京东',
      'VIP': '唯品会',
      'XP': '星品',
    },
    p_list: [
      { p: 'PDD', name: '拼多多' },
      { p: 'TB', name: '淘宝' },
      { p: 'JD', name: '京东' },
      { p: 'VIP', name: '唯品会' },
      { p: 'XP', name: '星品' },
    ],
	  Addpowder:false,  //添粉的隐藏显示
    price: 0,
    part_list: [],
    default_spec: [],
    allow_spec: [],
    selected_spec: [],
    selected_part: {},
    is_iphoneX: app.globalData.isIphonex,
    img_list: {},
	 
    level_code: '',
    zhuan_url: '', //转链 微信 short url
    show_tghb: false, // 推广海报促发 调用下载海报
    options: {},
    allowBuy: false,
    qrcode_img:'',
    select_list:[], //选择的 商品多图分享
    data:{
      video_info_high:{
        play_url:''
      },
      video_info_low:{
        play_url:''
      }
    }, //商品数据 
    share_title:'',
    current1:'',
    editing_title:'', // 正在编辑的文本框绑定
    level_1:'',
    level_2:'',
    opt:false,
    edit_title_focus:false, //分享编辑框 是否获取焦点
    edit_title_edit_icon:'/images/sale/moreves.png', //分享编辑 编辑模式图标
    edit_title_complete_icon:'/images/index/selectd.png', // 分享编辑 完成模式图标
    edit_title_icon:'/images/sale/moreves.png', // 编辑分享图标绑定
    guide:0,
    tg_generating:false,
    taoBaoAuthorizeCode:wx.getStorageSync('channelId') || '' // 淘宝渠道是否授权
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
	  console.log(options)
    console.log("====productDetail 传入参数:", options)
    console.log('=====query:',jsonParamToQueryStr(options))   
    log.info("====productDetail 传入参数:", options)

    if(options && options.scene){
        options.scene = decodeURIComponent(options.scene)
      
      if(options.scene.indexOf(',')!=-1){
        // 存在场景


         // 场景,用户uid
         let s_u=options.scene.split(',')
         let scene_id=s_u[0]  //场景ID
         let share_uid=s_u[1] // share_uid
         
         options.parent_uid=share_uid

        if(!app.globalData.share_uid){
          app.globalData.share_uid=share_uid
        }

       
         if(scene_id==8){  // 商品详情 小程序码
           let p=s_u[2]
           let item_id=s_u[3]
          
           options.id=item_id
           options.p=p
           

         }

      }

    }

    this.setData({
      options: options,
      show_share_xp: false,
      img_list: img_list,
    })

    var that = this;
    shareFun.hidenShareMenu();


    wx.showShareMenu({
      // withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    let cur_product;
    console.log('====options.scene:',options.scene)

    
    // 测试数据
   // let res_item =await goodsDetail({p:'JD',item_id:'70012066013'})
    //console.log('===分享加载商品数据:',res_item.data)
    //options.scene='8,10001,PDD,166943538297' //测试  商品二维码测试
    if(options && options.scene=='10001'){

      console.log('options.scene :',options.scene)
        // 小程序的分享
        this.data.fromOptions = options;
        options.parent_uid=options.share_uid
        await this.judgeLogin(options); // 登陆判断；如果未登陆先去登陆

        let p=options.p 
        let item_id=options.id
        let share_uid = options.share_uid
       
        

        if(p=='XP'){
          // await proDetail({ item_id: that.data.options.id, p: that.data.options.p })
          cur_product= await this.showXPDetail(item_id,p)
        }else{
          const { data } =await goodsDetail({p:p,item_id:item_id})

          console.log('===分享加载商品数据:',data)
          cur_product=data
        }
        

    }else if(options && options.scene && options.scene.indexOf(',')!=-1){
		console.log('商品详情');
        //  小程序码 推广分享 跳转到 productDetail
      var param =options.scene
      if(param && param.indexOf(',')!=-1){

        // 场景,用户uid
         let s_u=param.split(',')
         let scene_id=s_u[0]
         let share_uid=s_u[1]
         let p=s_u[2]
         let item_id=s_u[3]

         options.parent_uid=share_uid
         await this.judgeLogin(options); // 登陆判断；如果未登陆先去登陆

         if(p=='XP'){
       
          cur_product= await this.showXPDetail(item_id,p)
        }else{
          const { data } =await goodsDetail({p:p,item_id:item_id})

          console.log('===分享加载商品数据:',data)
          cur_product=data
        }
         
      }

    }
    else if (options && (options.wxlive_type == '0' || options.wxlive_type == '1')) { //直播间 过来的; 如果有 share_openid ，则是直播间分享来的
	console.log('直播来的');
      // 处理直播间分享 过来的商品详情
    // 只有直播间进入详情需要登陆
    // wxlive_type=0 直接点击链计进入
    // wxlive_type=1 分享链接进入
      this.data.fromOptions = options;
      await this.judgeLogin(options); // 登陆判断；如果未登陆先去登陆
      //await this.showDetail(); 
      // cur_product = this.cur_product

      /*
       if(options.share_openid && options.share_openid!=''){
           shareBind({record_id:options.room_id,openid:options.openid,parent_openid:options.share_openid,source_type:'C'})
       }*/

      if (options.p == 'XP') { 
        cur_product= await this.showXPDetail(options.id,options.p) //目前只有星品商品在直播间，所有这里先这样写
      } else {
        cur_product = app.globalData.cur_product
      }
    } else {
      //console.log('是这个');
      this.data.fromOptions = options;
    //  await this.judgeLogin(options); // 登陆判断；如果未登陆先去登陆; 只有直播或者分析的商品才需要判断权限 ，其她时候不需要权限

      if(app.globalData.cur_product==null || (!app.globalData.cur_product.p) || !app.globalData.cur_product.item_id){
       // await this.showDetail()
       const { data } =await goodsDetail({p:options.p,item_id:options.id})
       cur_product=data
       app.globalData.cur_product=data
        cur_product =app.globalData.cur_product
      }else{
        cur_product = app.globalData.cur_product
      }
     
	  
    }
    if (cur_product==null){
      cur_product=this.data.data
    }

    var level_code = app.globalData.userInfo.level_code
    this.setData({
      
      level_code: level_code,
    })
    that.topTipLoop()
	console.log('product detail:',cur_product);
    //var sale_prive = (cur_product.zk_price - (cur_product.coupon_min_avaliable < cur_product.zk_price ? cur_product.coupon_price : 0)).toFixed(2);
    var sale_prive=cur_product.qh_price.toFixed(2) //update by finder
    that.setData({
      fromOptions: options,
      sale_prive_1: sale_prive.split('.')[0],
      sale_prive_2: sale_prive.split('.')[1],
      data: cur_product,
      share: {
        img: cur_product.pict_main_url,
        title: cur_product.title
      }
    })
	
	console.log(this.data.data.coupon_price);
	 //if(this.data.data.coupon_price==0 && this.data.data.price!=this.data.data.zk_price)
	if(this.data.data.coupon_price>0){
		var bb='领券后:'+parseFloat(this.data.data.qh_price).toFixed(2)+'元，原价:'+parseFloat(this.data.data.zk_price).toFixed(2)+'元- 限购一件-'+this.data.data.title
	}else{
		var bb='领券后:'+parseFloat(this.data.data.qh_price).toFixed(2)+'元-限购一件-'+this.data.data.title
	}
	  
	console.log(bb);
	this.setData({
		level_1:bb
	})
	//console.log(this.data.level_1);
	
    if (cur_product.p == 'PDD') {//拼多多跳转小程序
      this.setData({
        btnArr: [
          { id: 0, index: 0, img: '/images/index/share_btn_icon1.png', text: '分享到微信', name: '小程序卡片', bind: '' },
          { id: 1, index: 1, img: '/images/index/share_btn_icon2.png', text: '保存海报(朋友圈)', name: '商品海报', bind: 'downloadImg1', tabTap: 'showTghb' },
          { id: 2, index: 2, img: '/images/index/share_btn_icon3.png', text: '保存选中图片', name: '商品多图', bind: 'downImg' },
        ],
        sliderLeft: 113,
        sliderOffset: 240,
        show: 1,
      })
    } else if (this.data.data.p == 'JD') {//京东跳转
      this.setData({
        btnArr: [
          { id: 0, index: 0, img: '/images/index/share_btn_icon1.png', text: '分享到微信', name: '小程序卡片', bind: '' },
          { id: 1, index: 1, img: '/images/index/share_btn_icon2.png', text: '保存海报(朋友圈)', name: '商品海报', bind: 'downloadImg1', tabTap: 'showTghb' },
          { id: 2, index: 2, img: '/images/index/share_btn_icon3.png', text: '保存选中图片', name: '商品多图', bind: 'downImg' },
        ],
        sliderLeft: 113,
        sliderOffset: 240,
        show: 1,
      })
    } else if (this.data.data.p == 'TB') {//淘宝生成淘口令
      this.setData({
        btnArr: [
          { id: 0, index: 0, img: '/images/index/share_btn_icon1.png', text: '分享到微信', name: '小程序卡片', bind: '' },
          { id: 2, index: 1, img: '/images/index/share_btn_icon3.png', text: '保存选中图片', name: '商品多图', bind: 'downImg' },
        ],
        sliderLeft: 177,
        sliderOffset: 354,
        show: 1,
      })
    } else if (cur_product.p == 'VIP') {//唯品会小程序
      this.setData({
        btnArr: [
          { id: 0, index: 0, img: '/images/index/share_btn_icon1.png', text: '分享到微信', name: '小程序卡片', bind: '' },
          { id: 1, index: 1, img: '/images/index/share_btn_icon2.png', text: '保存海报(朋友圈)', name: '商品海报', bind: 'downloadImg1', tabTap: 'showTghb' },
          { id: 2, index: 2, img: '/images/index/share_btn_icon3.png', text: '保存选中图片', name: '商品多图', bind: 'downImg' },
        ],
        sliderLeft: 113,
        sliderOffset: 240,
        show: 1,
      })
    } else if (this.data.data.p == 'XP') { //星品生活
      // console.log('p=', this.data.data.p)
      // this.setData({
      //   show: 1
      // })
	  this.setData({
	    btnArr: [
	      { id: 0, index: 0, img: '/images/index/share_btn_icon1.png', text: '分享到微信', name: '小程序卡片', bind: '' },
	      { id: 1, index: 1, img: '/images/index/share_btn_icon2.png', text: '保存海报(朋友圈)', name: '商品海报', bind: 'downloadImg1', tabTap: 'showTghb' },
	      { id: 2, index: 2, img: '/images/index/share_btn_icon3.png', text: '保存选中图片', name: '商品多图', bind: 'downImg' },
	    ],
	    sliderLeft: 113,
	    sliderOffset: 240,
	    show: 1,
	  })
    }
    this.page = 1
    this.canLoadMore = true;
    setTimeout(function () {
      const query = wx.createSelectorQuery();
      query.select('.detail_top1').boundingClientRect();
      query.exec((res) => {
        if(res && res[0]){// update by finder
          that.setData({
            menuTop: res[0].top - app.globalData.CustomBar,
          })
        }
        
      });
    }, 2000)
    let { data } = await search({ q: cur_product.cid_name || '', p: '', page_index: this.page, page_size: 8 })

    let list =data
    if (list){

      if (list.length%2!=0){
        // delete liveData.data[liveData.data.length-1] //删除最后一个
        list.pop()
      }
    }
	


    this.setData({
      productList: list.length > 8 ? list.slice(0, 8) : list,
    })
    saveVisit({ keyword: cur_product.title, user_id: app.globalData.uid, item_id: cur_product.item_id, item_url: cur_product.item_url, cid_name: cur_product.cid_name, p: cur_product.p })
    that.getBuyList();
	// this.homepageguide();
	
	
	
 
  },
  closeIn(){
  	  this.setData({
  		  In:false
  	  });
  },
  async homepageguide() {
    let top_banner = await getBanner({ group_code: 'guide_prod' });
  	if(top_banner.data==null || top_banner.data==[]){
  		this.setData({
  			guide:1
  		})
  		return;
  	}
  	// var result=top_banner.data[0].extras.split(",");
   //  this.setData({
  	// 	guide_idx:top_banner.data[0].url,
  	// 	guide_top:result[0],
  	// 	guide_left:result[1]
  	// })
  	console.log(top_banner);
  },
  saveShareTitle(){
    console.log('------- saveShareTitle')
	  if(this.data.pop==false){
		  this.setData({   
        pop:true,
        edit_title_focus:true,
        edit_title_icon:this.data.edit_title_complete_icon,

		  })
	  }else{

      console.log('=====字数:',this.data.editing_title.length)
      if(this.data.editing_title.length>32){
        
        wx.showToast({
          title: '字数超过了',
        })
        return ;
      }

		  this.setData({
		  	level_1:this.data.editing_title,
            pop:false,
            edit_title_focus:false,
            edit_title_icon:this.data.edit_title_edit_icon,
		  })
	  }
	  console.log(this.data.level_1);
		  
  },
  inputedit_sharetitle(e) {
    var value = e.detail.value;
    console.log('----inputedit_sharetitle 长度:',value)
    this.setData({
      editing_title: value
    })
    if(value.length>32){
      wx.showToast({
        title: '字数超过了',
      })
    }
  }, 
  inputeditd(e){
	  var value = e.detail.value;
	  this.setData({
	  	level_2: value
	  })
  },
  // 动画函数
    chooseSezi: function (e) {
      var animation=wx.createAnimation({
		  duration:2000,
		  timingFunction:'ease'
	  })
	  animation.translateY(0).step()
	  this.setData({
		  current1:animation.export(),
		  pop:true
	  })
    },
  getSpec(data) {
    const specList = data.spec_detail;
    const specItems = this.getSpecTitle(data.spec_title); //生成规格对象
    let arr1 = Array.from({ length: specItems.length }, () => []);//按规格分类保存规格信息
    let arr2 = [];
    let arr3 = Array.from({ length: specList.length }, () => []);//按商品保存规格信息
    specList.forEach((item, index) => {
      let i = 0;
      for (let key in item) {
        if (/spec\d/.test(key)) {//抽取商品信息中的规格信息
          arr1[i].push(item[key]);
          arr3[index].push(item[key]);
          i++;
        }
      }
    })
    for (let i in arr1) {
      arr1[i] = [...new Set(arr1[i])]
      arr2 = [...arr2, ...arr1[i]]
    }
    arr1.forEach((item, index) => {
      item.forEach((_item, _index) => {
        let obj = {};
        obj.is_allow = 1;
        obj.name = _item;
        specItems[index].list.push(obj);
      })
    })
    console.log(arr1, arr2)
    const specVertex = new SpecVertex(arr2);
    arr3.forEach((item) => {//遍历每件商品的规格信息，注册规格关系
      item.forEach((_item, _index) => {
        const temp = JSON.parse(JSON.stringify(item));
        temp.splice(_index, 1);
        specVertex.setJoinVertexs(_item, temp);
      })
    })
    this.setData({
      specVertex: specVertex
    })
    return specItems;
  },
  getSpecTitle(specTitle) {
    const res = [];
    for (let key in specTitle) {
      if (/spec\d/.test(key)) {
        console.log(key, specTitle[key])
        res.push({
          title: specTitle[key],
          list: []
        })
      }
    }
    return res
  },
  longPress(e){
	console.log(e);
	wx.setClipboardData({
	    data: e.currentTarget.dataset.title,
	    success: function (res) {	
	      wx.getClipboardData({	
	        success: function (res) {	
	          console.log('复制成功'); // data
	        }	
	      })	
	    }	
	  })
  },
  async showXPDetail(item_id,p){ // 显示星品商品信息
    let cur_product={}
   // const { data } = await proInfo({ item_id: item_id,p:'XP' })
   const { data } = await goodsDetail({ item_id: item_id,p:p })
    const goods=data
    console.log(goods);

    if(!goods.pict_main_url.startsWith('http')){
      goods.pict_main_url='http:'+goods.pict_main_url
    }

    if(goods.desc_images!=null && goods.desc_images.length!=0){

     /* for (var i=0;i<goods.desc_images.length;i++){
        if(!goods.desc_images[i].startsWith('http')){
          goods.desc_images[i]='http:'+goods.desc_images[i]
        }
      }*/
    }

    cur_product = goods;
    const specItems = this.getSpec(goods);
    let amount = 0;
    goods.spec_detail.forEach(item => {
      amount += item.amount;
    })
    this.setData({
      specDetail: goods.spec_detail,
      part_list: specItems,
      default_amount: amount,
      amount: amount,
      price: cur_product.zk_price,
    
    })

    return cur_product
  },


  async share_mlm(options) { //分享建立用户关系
    if (options) {
      if (options.share_openid != '' && options.share_openid != undefined) {
        let live_id = options.room_id
        let open_id = options.openid
        let share_openid = options.share_openid
        let custom_params = options.custom_params
      }
    }

  },
  opening() {
    if (this.data.level_code == '0') {
      wx.navigateTo({
       url: '/pages/module/growth/growth',
      })
    } else {
      wx.navigateTo({
        url: '/pages/module/growth/growth',
      })
    }
  },
  judgeLogin(options) {
    var that = this;
    return new Promise(async (resolve, reject) => {
      let userInfo, uid, token
      try {
        uid = await getData(dataKey.uid);
        app.globalData.uid = uid;
        token = await getData(dataKey.token);
        // app.globalData.token = token;en;
        wx.setStorageSync('token', token)

        userInfo = await getData(dataKey.userInfo);
        app.globalData.userInfo = userInfo;
      } catch (error) {

      }
      if (uid) {
        resolve()
      } else {

        wx.showLoading({
          title: '授权中...',
        })

        wx.login({
          success: async ({ code }) => {

            wx.hideLoading({
              success: (res) => { },
            })

            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            const rdata = await login(code);
            if (rdata.code == '0') {
              await setData(dataKey.token, rdata.data.access_token);
              uid = rdata.data.uid
              // app.globalData.token = rdata.data.access_token
              wx.setStorageSync('token', rdata.data.access_token)
              await setData(dataKey.session_key, rdata.data.session_key);
              app.globalData.session_key = rdata.data.session_key
              if (uid) {
                await setData(dataKey.uid, rdata.data.uid);
                await setData(dataKey.userInfo, rdata.data)
                app.globalData.userInfo = rdata.data;
                app.globalData.userInfo.uid = uid;
                setData('userInfo', app.globalData.userInfo)
                if (!app.is_auth()) {
                  that.data.is_login_back = true

                /*  var pages = getCurrentPages() //获取加载的页面
                  var currentPage = pages[pages.length-1] //获取当前页面的对象
                  var url = currentPage.route //当前页面ur
                  options.redirect_url=url
                  */
                  wx.navigateTo({
                    url: '/pages/login/login?' + jsonParamToQueryStr(options),
                  })
                  return;
                }
                resolve()
              } else {
                resolve()
                // 获取用户信息
                wx.getSetting({
                  success: async res => {
                    if (res.authSetting['scope.userInfo']) {
                      // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                      wx.getUserInfo({
                        withCredentials: true,
                        success: async res => {
                          res.parent_openid = options.share_openid
                          res.code = code
                          await that.onGetUserInfo({
                            detail: res,
                          });




                        }
                      });
                    } else {
                      that.data.is_login_back = true
                      var pages = getCurrentPages() //获取加载的页面

                      var currentPage = pages[pages.length-1] //获取当前页面的对象
    
                      var url = currentPage.route //当前页面ur
                      options.redirect_url=url
                      
                      wx.navigateTo({
                        url: '/pages/login/login?' + jsonParamToQueryStr(options),
                      })
                    }
                  },
                });
                // this.setData({ renderType: 1 });
              }
              wx.hideLoading();
            } else {
              console.error(result);
            }
          },
          fail: err => {
            console.log(err);
          },
        });
      }
    })
  },
  onGetUserInfo: async function ({ detail: { errMsg, userInfo, encryptedData, iv, code, parent_openid } }) {
    const { data } = await getUserData(encryptedData, iv, code, parent_openid,'');
    await setData(dataKey.userInfo, data)
    app.globalData.userInfo = data;
    await setData(dataKey.uid, data.uid)
    app.globalData.uid = data.uid;
    await setData(dataKey.session_key, data.session_key);
    app.globalData.session_key = data.session_key
    await setData(dataKey.token, data.access_token);
    // app.globalData.token = data.access_token
    wx.setStorageSync('token', data.access_token)
  },
  async getBuyList() {
    var that = this;
    let { data } = await getBarrage() 
    that.setData({
      buy_index: -1,
      buy_list: data,
    }, () => {

      // 防止快速死循环

      // 先注释 ，在打开
      // setTimeout(function () {
      //   that.topTipLoop()
      // }, 2000)

    })
  },
  topTipLoop() {
    var that = this;
    that.data.buy_index++
    if (that.data.buy_index >= this.data.buy_list.length) {
      //请求接口
      this.data.buy_list = []
      that.data.buy_index = -1
      that.getBuyList();
      return;
    }
    that.setData({
      show_buy: true,
      buy_index: that.data.buy_index
    })
    clearTimeout(setT1)
    clearTimeout(setT2)
    clearTimeout(setT3)
    setT1 = setTimeout(function () {
      that.setData({
        show_buy_active: true,
      })
    }, 500)
    setT2 = setTimeout(function () {
      that.setData({
        show_buy: false,
        show_buy_active: false,
      })
    }, 2000)
    setT3 = setTimeout(function () {
       that.topTipLoop()// 先注释
    }, 5000)
  },
  onPageScroll: function (e) {
    var that = this;
    this.scrollTop = e.scrollTop
	
	console.log(e);
	
    this.getSmallVideo(e.scrollTop);
    if (e.scrollTop >= 700) {
      if (!this.data.show_video && this.data.data.video_info_high.play_url) {
        this.data.show_video = true;
        this.setData({
          show_video: true,
        })
      }
    } else {
      if (this.data.show_video && this.data.data.video_info_high.play_url) {
        this.data.show_video = false;
        that.setData({
          show_video: false,
        })
      }
    }
    if (this.data.is_show_detail == 0) {
      if (e.scrollTop >= this.data.image_box_top) {
        if (this.data.tabIndex1 == 1) return;
        that.setData({
          tabIndex1: 1,
        })
      } else {
        if (e.scrollTop < this.data.menuTop) {
          if (!that.data.menuFixed) {
            if (e.scrollTop >= 200) {
              if (this.data.show_go_top) return
              this.setData({
                show_go_top: true
              })
              setTimeout(function () {
                that.setData({
                  show_go: true
                })
              }, 500)
            } else {
              if (!this.data.show_go_top) return
              this.setData({
                show_go: false
              })
              setTimeout(function () {
                that.setData({
                  show_go_top: false
                })
              }, 500)
              return;
            }
          }
          that.setData({
            menuFixed: false
          })
        } else {
          if (!this.data.tabIndex1 == 0) {
            that.setData({
              tabIndex1: 0,
              menuFixed: true
            })
          }
          if (that.data.menuFixed) return
          that.setData({
            menuFixed: true
          })
        }
      }
      return
    }
    if (e.scrollTop >= this.data.menuTop - app.globalData.screenHeight) {
      if (this.data.main_images) return
      this.showDetail();
    }
    if (e.scrollTop >= this.data.menuTop) {
      if (this.data.menuFixed) return;
      var tabIndex1 = 0
      if (this.data.is_show_detail == 1) {
        tabIndex1 = 1
      }
      that.setData({
        tabIndex1,
        image_box_top: that.data.image_box_height ? that.data.image_box_top : that.data.menuTop,
        menuFixed: true
      })
    } else {
      if (!this.data.menuFixed) {
        if (e.scrollTop >= 200) {
          if (this.data.show_go_top) return
          this.setData({
            show_go_top: true
          })
          setTimeout(function () {
            that.setData({
              show_go: true
            })
          }, 500)
        } else {
          if (!this.data.show_go_top) return
          this.setData({
            show_go: false
          })
          setTimeout(function () {
            that.setData({
              show_go_top: false
            })
          }, 500)
        }
        return;
      }
      that.setData({
        menuFixed: false
      })
    }
  },
  getSmallVideo(num) {
    if (num > this.data.small_y) {
      if (this.data.smallVideo) return
      this.setData({
        smallVideo: true,
      })
    } else {
      if (!this.data.smallVideo) return
      this.setData({
        smallVideo: false,
      })
    }
  },
  async showDetail() {
    var that = this;
    return new Promise(async (resolve, reject) => {
     // if (that.data.fromOptions.p === 'XP') return;
      if (that.data.main_images) {
        //console.log('2')
        that.data.menuFixed = false;
        resolve();
        that.setData({
          show: 1,
          is_show_detail: 0,
        }, () => {
          if (that.data.image_box_height) return;
          if (that.data.is_show_detail == 1) return;
          setTimeout(function () {
            const query1 = wx.createSelectorQuery();
            query1.select('.image_box').boundingClientRect();
            query1.exec((res) => {
              that.setData({
                image_box_height: res[0].height,
                image_box_top: res[0].height + that.data.menuTop,
              })
            });
          }, 1000)
        })
        return;
      }
      // if(this.data.data.desc_load) return;
      if (that.data.is_load) return
      that.data.is_load = true;
      that.setData({
        is_load: true
      })

      let cur_product =null
      if(!this.data.data || !this.data.data.desc_load){
        const { data } = await goodsDetail({ item_id: that.data.options.id, p: that.data.options.p })
        // const { data } = await goodsDetail({ item_id: '102', p: that.data.fromOptions.p })
        if(data!=null && !data.video_info_high.play_url){ //update by finder 20200906
            data.video_info_high= that.data.data.video_info_high
            data.video_info_low=that.data.data.video_info_low
        }
        
        cur_product=data
      }else{
        cur_product=this.data.data
      }
      
      this.setData({
        data:cur_product
      })
     
      resolve();
      var new_arr = [], new_arr1 = [];
	  
      that.data.data.desc_images.forEach(item => {
        var obj = {}
        obj.path = item;
        obj.imgShow = false
        obj.src = item.indexOf('http') > -1 ? item : 'http:' + item;
        obj.select = 1
        new_arr.push(obj)
        new_arr1.push(obj)
      });
      /*if (that.data.share_img) {
        if (new_arr.length <= 6) {
          new_arr[1] = { src: that.data.qrcode_img, select: 1 }
        } else {
          new_arr[4] = { src: that.data.qrcode_img, select: 1 }
        }
      }*/
	  if(new_arr.length >= 9){
      for(var i=6;i<=9;i++){
        if(new_arr[i]){
          new_arr[i].imgShow=true
        }
      }
		  
	  }
	  
	  
	  console.log(new_arr);
      if (that.data.qrcode_img) {
        if (new_arr.length <= 6) {
          new_arr[1] = { src: that.data.qrcode_img, select: 1,imgShow:true,path: that.data.qrcode_img}
        } else {
          new_arr[4] = { src: that.data.qrcode_img, select: 1 ,imgShow:true,path: that.data.qrcode_img}
        }
      }
	  

      that.data.menuFixed = false;
      that.setData({
        show: 1,
        is_load: false,
        is_show_detail: 0,
        main_images: new_arr1,
        select_list: new_arr,
        new_arr,
      }, () => {
        if (that.data.image_box_height) return;
        if (that.data.is_show_detail == 1) return;
        setTimeout(function () {
          const query1 = wx.createSelectorQuery();
          query1.select('.image_box').boundingClientRect();
          query1.exec((res) => {
            that.setData({
              image_box_height: res[0].height,
              image_box_top: res[0].height + that.data.menuTop,
            })
          });
        }, 1000)
      })
      wx.hideLoading({})
    })
  },
  async getCouponBuy() {
    // console.log(1111)

    if (!app.is_auth()) {
      wx.navigateTo({
        url: '/pages/login/login?' + jsonParamToQueryStr(this.data.options),
      })
      return;
    }

    if (this.data.fromOptions.p === 'XP') {
      this.setData({
        show_part: true
      })
    } else {
      this.convert1(true)
    }
  },
  async convert1(is_coupon) { //true 表示领取优惠券转链   false表示分享转链
    var that = this;
    if (app.globalData.userInfo.uid == '0' || app.globalData.userInfo.uid == '') {
      wx.navigateTo({
        url: '/pages/login/login?' + jsonParamToQueryStr(this.data.options),
      })
      return;
    }



    // update 20200805 0810
    // 转链 解决 level_code="0", 购买不做推手， 推手来自上级
    var uid = ""
    var buyer_uid = ""

    let userInfo = await getData('userInfo')


    if (is_coupon) {
      console.log('=====uid level_code:'+app.globalData.userInfo.level_code)
      if (app.globalData.userInfo.level_code == "0") {
        buyer_uid = userInfo.uid
        let {data} = await get_near_spreader({uid:userInfo.uid})  //获取最近的 推手 updateby finder 20200909
        uid=data

        console.log('======= 最近的推客uid:'+uid)
      } else {
        buyer_uid = userInfo.uid
        uid = userInfo.uid
      }

    } else {
      buyer_uid = ""
      uid = userInfo.uid
    }


    var _is_coupon = is_coupon;
    if (this.data.data.p == 'PDD') {//拼多多跳转小程序
      if (this.data.app_id) {
        if (_is_coupon) {
          this.setData({
            show_load: true
          })
          wx.navigateToMiniProgram({
            appId: this.data.app_id,
            path: this.data.wxapp_page_path,
            success(res) {
              that.setData({
                show_load: false
              })
            },
            fail() {
              that.setData({
                show_load: false
              })
            }
          })
        } else {
          this.setData({
            zhuan_url: this.data.zhuan_url,
            show_share: true
          })
        }
        return
      }
      wx.showLoading({
        title: '加载中',
      })



      const { data } = await convert({
        p: this.data.data.p,
        content: this.data.data.item_id,
        uid: uid,
        buyer_uid: buyer_uid
      })

      console.log(data);

      if (_is_coupon) {
        wx.navigateToMiniProgram({
          appId: data.app_id,
          path: data.wxapp_page_path,
          success(res) {
            that.setData({
              show_load: false
            })
          },
          fail() {
            that.setData({
              show_load: false
            })
          }
        })
        this.setData({
          show_load: true,
          app_id: data.app_id,
          wxapp_page_path: data.wxapp_page_path,
          zhuan_url: data.we_app_web_view_short_url,
        })
      } else {
        this.setData({
          zhuan_url: data.we_app_web_view_short_url,
          app_id: data.app_id,
          wxapp_page_path: data.wxapp_page_path,
          show_share: true
        })
      }
      wx.hideLoading({})
    } else if (this.data.data.p == 'JD') {//京东转链
      if (this.data.jd_app_id) { // 已经转链
        if (_is_coupon) {
          this.setData({
            show_load: true
          })
          wx.navigateToMiniProgram({
            appId: this.data.jd_app_id,
            path: this.data.jd_wxapp_page_path,
            success(res) {
              that.setData({
                show_load: false
              })
            },
            fail() {
              that.setData({
                show_load: false
              })
            }
          })
        } else {
          this.setData({
            zhuan_url: this.data.zhuan_url,
            show_share: true
          })
        }
        return
      }

      // 还未转链
      wx.showLoading({
        title: '加载中',
      })
      // 京东有的有券有的没有，还需要选择最小的金额的券
      let _coupon_url = ""
      if (this.data.data.coupon_url == "") {
        _coupon_url = ""
      } else if (this.data.data.coupon_min_avaliable < this.data.data.zk_price) {
        _coupon_url = this.data.data.coupon_url
      }





      const { data } = await convert({
        coupon_url: _coupon_url,
        p: this.data.data.p,
        content: this.data.data.item_url,
        uid: uid,
        buyer_uid: buyer_uid
      })
      if (_is_coupon) {
        wx.navigateToMiniProgram({
          appId: data.app_id,
          path: data.wxapp_page_path,
          success(res) {
            that.setData({
              show_load: false
            })
          },
          fail() {
            that.setData({
              show_load: false
            })
          }
        })
        this.setData({
          show_load: true,
          jd_app_id: data.app_id,
          jd_wxapp_page_path: data.wxapp_page_path,
          zhuan_url: data.we_app_web_view_short_url,
        })
      } else {
        this.setData({
          zhuan_url: data.we_app_web_view_short_url,
          jd_app_id: data.app_id,
          jd_wxapp_page_path: data.wxapp_page_path,
          show_share: true
        })
      }
      wx.hideLoading({})
    } else if (this.data.data.p == 'TB') {//淘宝生成淘口令

      if(app.globalData.configs.tb_relation_enable=='1'){
        if(wx.getStorageSync('channelId')==""){
          
          wx.showModal({
            title: '授权提示',
            content: '淘宝商品只有授权之后才可以获利',
            showCancel:'true',
            confirmText:'前往授权',
            confirmColor:'#8029eb',
             success (res) {
               if (res.confirm) {
               wx.navigateTo({
                       url:'/packageTab/pages/TaoBao_Authorize/TaoBao_Authorize?uid='+app.globalData.userInfo.uid
               })
               } else if (res.cancel) {
                 console.log('用户点击取消')
                //  if (this.data.fromOptions.p === 'XP') {
                //   this.setData({
                //     show_part: true
                //   })
                // } else {
                //   this.convert1(true)
                // }
               }
               
             }
           })
           return
        }

      }
     
      if (this.data.zhuan_url) { //修改 coupon_tpwd 到zhuan_url


        

        if (_is_coupon) {
          this.setData({
            is_show_big: 1
          })
        } else {
          this.setData({
            show_share: true
          })
        }
        return
      }
      wx.showLoading({
        title: '加载中',
      })
      const { data } = await convert({
        p: this.data.data.p,
        content: this.data.data.item_id,
        uid: uid,
        buyer_uid: buyer_uid
      })
      if (_is_coupon) {
        this.setData({
          zhuan_url: data.coupon_tpwd,
          is_show_big: 1
        })
      } else {
        this.setData({
          zhuan_url: data.coupon_tpwd,
          show_share: true
        })
      }
      wx.hideLoading({})
    } else if (this.data.data.p == 'VIP') {//唯品会跳转小程序
      if (this.data.vip_app_id) {
        if (_is_coupon) {
          this.setData({
            show_load: true
          })
          wx.navigateToMiniProgram({
            appId: this.data.vip_app_id,
            path: this.data.vip_wxapp_page_path,
            success(res) {
              that.setData({
                show_load: false
              })
            },
            fail() {
              that.setData({
                show_load: false
              })
            }
          })
        } else {
          this.setData({

            show_share: true
          })
        }
        return
      }
      wx.showLoading({
        title: '加载中',
      })
      const { data } = await convert({
        p: this.data.data.p,
        content: this.data.data.item_id,
        uid: uid,
        buyer_uid: buyer_uid
      })
      if (_is_coupon) {
        wx.navigateToMiniProgram({
          appId: data.app_id,
          path: data.wxapp_page_path,
          success(res) {
            that.setData({
              show_load: false
            })
          },
          fail() {
            that.setData({
              show_load: false
            })
          }
        })
        this.setData({
          show_load: true,
          vip_app_id: data.app_id,
          vip_wxapp_page_path: data.wxapp_page_path,
          zhuan_url: data.we_app_web_view_short_url,
        })
      } else {
        this.setData({
          zhuan_url: data.we_app_web_view_short_url,
          vip_app_id: data.app_id,
          vip_wxapp_page_path: data.wxapp_page_path,
          show_share: true
        })
      }
      wx.hideLoading({})
    } else if (this.data.data.p == 'XP') {
      console.log('星品平台分享111')
      this.setData({   // update by 20201010 
        show_share_xp: true
      })
      

      // 星品的商品也走默认的分享模式
     /* const { data } = await convert({
        p: this.data.data.p,
        content: this.data.data.item_id,
        uid: uid,
        buyer_uid: buyer_uid
      })

      

      this.setData({
        zhuan_url: data.we_app_web_view_short_url,
        xp_app_id: data.app_id,
        xp_wxapp_page_path: data.wxapp_page_path,
        show_share: true
      })*/

   //    if(!this.data.zhuan_url){
   //    	var zhuan_url='pages/module/productDetail/productDetail';
   //    }else{
   //    	var zhuan_url=this.data.zhuan_url
   //    }
	  
	   this.setData({
		   zhuan_url: 'pages/module/productDetail/productDetail',
	       qrcode_img: text2qr({text:'pages/module/productDetail/productDetail'})
	   })

      return 
    }


   // console.log('=========qrcodeimg:',text2qr({text:this.data.zhuan_url}))
   
  
    this.setData({
      qrcode_img: text2qr({text:this.data.zhuan_url})
    })
  },
  async showImg(e) { // 由show_tghb 这个属性 变化 调用的

    if (this.data.new_arr.length <= 6) {
     // this.data.new_arr[1] = { src: e.detail.qrcode_img, select: 1 }
       this.data.new_arr[1] = {src:this.data.qrcode_img,select:1,imgShow:true,path:this.data.qrcode_img}
    } else {
     // this.data.new_arr[4] = { src: e.detail.qrcode_img, select: 1 }
       this.data.new_arr[4] = {src:this.data.qrcode_img,select:1,imgShow:true,path:this.data.qrcode_img}
    }
    this.setData({
     // qrcode_img: e.detail.qrcode_img, 这个通过canvas  本地生成； 需要更新到服务器生成 ; update by finder
      share_img: e.detail.url,
      new_arr: this.data.new_arr
    })


    if (this.data.p == 'TB') {
      return
    }

    wx.showLoading({
      title: '商品海报生成中...',
    })
	
    // 后端显示推广码 update 20200810
	console.log('是这2');
	console.log(this.data.share_img);
	// if(!this.data.zhuan_url){
	// 	var zhuan_url='pages/module/productDetail/productDetail';
	// }else{
	// 	var zhuan_url=this.data.zhuan_url
	// }
	
    const link_data = await goods_shareimg_post({
      goods_picture_url: this.data.data.pict_main_url,
      goods_link_url: this.data.zhuan_url,
      goods_detail: this.data.data.title,
      platform_price: this.data.data.qh_price,
      market_price: this.data.data.zk_price==this.data.data.qh_price?this.data.data.price:this.data.data.zk_price,
      ticket: this.data.data.coupon_price,
      uid: app.globalData.userInfo.uid,
    })
    console.log(link_data);
    wx.hideLoading({
      success: (res) => { },
    })


    // console.log("==商品推广海报:" + link_data)
    this.setData({
      share_img: link_data.data
    })
  },
  async powder(){ //点击 切换 添粉分享
	  if (!app.is_auth()) {
      wx.navigateTo({
        url: '/pages/login/login?' + jsonParamToQueryStr(this.data.options),
      })
      return;
    }
    //qrcode_img_haibao='/pages/module/productDetail/productDetail?id=' + this.data.data.item_id + '&p=' + this.data.data.p + '&scene=10001&share_uid=' + app.globalData.userInfo.uid
    //qrcode_img_haibao=""
  
    let Addpowder=!this.data.Addpowder

    if(Addpowder){
      if(app.globalData.configs.is_weapp_qr_fans_generator=='0'){
          wx.showToast({
            title: '圈粉分享明日开放',
          })
          return 
      }
    }

    this.setData({
        Addpowder:Addpowder
    })
    
    
    let link_url=""
    let scene=""
    if(Addpowder){
        // 添粉丝

        

        link_url='pages/module/productDetail/productDetail'
        scene="8,"+app.globalData.userInfo.uid+","+this.data.data.p+","+this.data.data.item_id // 场景id,share_uid,平台,商品item_id => 8,10001,PDD,6918702580860576773
        
        
        let qrcode_img='' //用作 商品多图的时候
        qrcode_img = mini_img({path:link_url,scene:scene})

        console.log('===scene:'+scene)
        console.log('----qrcode_img:'+qrcode_img)
        //获取二维码商品小程序分享码
        this.setData({
          qrcode_img:qrcode_img
        })
        this.updateMutilImgQr()
    }else{
        // 购物
        link_url=this.data.zhuan_url

        let image_url= text2qr({text:this.data.zhuan_url})
        this.setData({
          qrcode_img:image_url
        })

        this.updateMutilImgQr()
    }
    
    wx.showLoading({
      title: '商品推广海报生成中...',
    })

    if(this.data.cur_btn_index==1){ // 推广海报的时候TAB再生成
         // 后端显示推广码 update 20200810
	
      const link_data = await goods_shareimg_post({
        goods_picture_url: this.data.data.pict_main_url,
        goods_link_url: link_url,
        goods_detail: this.data.data.title,
        platform_price: this.data.data.qh_price,
        market_price: this.data.data.zk_price,
        ticket: this.data.data.coupon_price,
        uid: app.globalData.userInfo.uid,
        scene:scene
      })
      this.setData({
        share_img: link_data.data
      })
   

    }
    wx.hideLoading({
      success: (res) => { },
    })
  
   
    


  },

  updateMutilImgQr:function(){

     if (this.data.new_arr.length <= 6) {
      // this.data.new_arr[1] = { src: e.detail.qrcode_img, select: 1 }
        this.data.new_arr[1] = {src:this.data.qrcode_img,select:1,imgShow:true,path:this.data.qrcode_img}
     } else {
      // this.data.new_arr[4] = { src: e.detail.qrcode_img, select: 1 }
        this.data.new_arr[4] = {src:this.data.qrcode_img,select:1,imgShow:true,path:this.data.qrcode_img}
     }

     this.setData({
      
       new_arr: this.data.new_arr
     })
  },

  goServe() {
    wx.navigateTo({
      url: '/pages/module/serveDesc/serveDesc',
    })
  },
  closeDown() {
    this.setData({
      is_show_big1: 0,
      is_show_big: 0
    })
  },
  async vipShareBuy() {
	 // console.log('是这个');
    if (!app.is_auth()) {
      wx.navigateTo({
        url: '/pages/login/login?' + jsonParamToQueryStr(this.data.options),
      })
      return;
    }

   // if (this.data.data.p !== 'XP'){
    if (this.data.data.p !== '都执行'){
      //console.log('分享一下');
        //await this.showDetail(); //update by finder 20200918
        this.showDetail(); //异步试试,不执行 showDetail的话， 9图 没有详情图 就变成非9图 ;异步执行测试成功，加快打开速度
        this.convert1(false)
        //console.log(this.data.price)
        //var bb='领券后:'+parseFloat(this.data.data.qh_price).toFixed(2)+'元，而原价:'+parseFloat(this.data.data.price).toFixed(2)+'元-限购一件-'+this.data.data.title
       var bb =''
        if(this.data.data.coupon_price>0){
        	bb='领券后:'+parseFloat(this.data.data.qh_price).toFixed(2)+'元，原价:'+parseFloat(this.data.data.zk_price).toFixed(2)+'元-限购一件-'+this.data.data.title
        }else{
        	bb='领券后:'+parseFloat(this.data.data.qh_price).toFixed(2)+'元-限购一件-'+this.data.data.title
        }
      //{{data.title}}\n  {{ ()?'【推荐理由】:'+data.short_title:''}} \n\n 【星品优惠价】{{numberUtil.numberFixed()}}元\n 【原价】{{data.zk_price}}元\n\n  {{ data.p=='TB' ?'复制淘口令，打开手机淘宝购买' :'商品链接:'}}  {{zhuan_url}}\n\n
      // var value = parseFloat(this.data.data.zk_price-this.data.data.coupon_price);
      //  value.toFixed(2);
      // 
      // if(this.data.data.short_title!=''  && this.data.data.short_title!=this.data.data.title){
      // 	if(this.data.data.p=='TB'){
      // 		var cc=this.data.data.title+'\n【推荐理由】:'+this.data.data.short_title+'\n\n【星品优惠价】'+value+'元\n 【原价】'+this.data.data.zk_price+'元\n\n复制掏口令，打开手机淘宝购买'+this.data.zhuan_url+'\n\n'
      // 	}else{
      // 		var cc=this.data.data.title+'\n【推荐理由】:'+this.data.data.short_title+'\n\n【星品优惠价】'+value+'元\n 【原价】'+this.data.data.zk_price+'元\n\n商品链接:'+this.data.zhuan_url+'\n\n'
      // 	}
        
      // }else{
      // 	if(this.data.data.p=='TB'){
      // 		var cc=this.data.data.title+'\n【推荐理由】:'+this.data.data.short_title+'\n\n【星品优惠价】'+value+'元\n 【原价】'+this.data.data.zk_price+'元\n\n复制掏口令，打开手机淘宝购买'+this.data.zhuan_url+'\n\n'
      // 	}else{
      // 		var cc=this.data.data.title+'\n\n\n【星品优惠价】'+value+'元\n 【原价】'+this.data.data.zk_price+'元\n\n商品链接:'+this.data.zhuan_url+'\n\n'
      // 	}
      // }
      var cc=bb.substring(0,36)
      console.log(cc)
      this.setData({
        editing_title:cc,
        level_1:bb
        
      })
    }
  },
  hideShare() {
    this.setData({
      show_share: false,
	  show_share_xp: false
    });
	this.setData({
	  show_part: false,
	  flex_center:false
	})
  },
  goUrl(e) {
    var url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: '/pages/common/h5/webview/webview?url=' + url
    })
  },
  oupd(){
	   this.setData({
	  	 opt:!this.data.opt
	   })
	  // if(this.data.opt==false){
		 //  this.setData({
			//   opt:true
		 //  })
	  // }else{
		  
	  // }
  },
  goIndex() {
    wx.switchTab({
      url: '/pages/tabbar/index/index',
    })
  },
  showPoster() {
    this.setData({
      show_poster: 1
    })
  },
  hidePoster() {
    this.setData({
      show_poster: 0
    })
  },
  minus() {
    this.setData({
      part_count: (this.data.part_count - 1) == 0 ? 1 : (this.data.part_count - 1)
    })
  },
  add() {
    this.setData({
      part_count: (this.data.part_count + 1) > this.data.amount ? this.data.amount : (this.data.part_count + 1)
    })
  },
  minus1() {
    this.setData({
      part_count1: (this.data.part_count1 - 1) == 0 ? 1 : (this.data.part_count1 - 1)
    })
  },
  add1() {
    this.setData({
      part_count1: (this.data.part_count1 + 1) > this.data.amount1 ? this.data.amount1 : (this.data.part_count1 + 1)
    })
  },
  gopart(){
	this.setData({
		flex_center:true
	})  
  },
  choosePart(e) {
    var isAllow = e.currentTarget.dataset.allow;
    if (!isAllow) return
    var p_index = e.currentTarget.dataset.p_index;
    var name = e.currentTarget.dataset.name;
    const allow = this.data.specVertex.getJoinVertexs(name);
    console.log(allow)
    const target = p_index == 0 ? 1 : 0;
    this.data.part_list[p_index].list.forEach(item => {
      item.is_allow = 1;
    });
    for (let i in this.data.part_list) {//遍历规格分类信息
      if (i == p_index) {//将选中的规格设置到所属分类的selected中
        this.data.selected_spec[i] = name
      } else {
        this.data.selected_spec[i] = allow.includes(this.data.selected_spec[i]) ? this.data.selected_spec[i] : '';
      }
    }
    this.setData({
      selected_spec: this.data.selected_spec,
      part_list: this.data.part_list
    }, () => {
      let amount, price, part, allowBuy = false;
      //如果所有规格都选择了
      if (this.data.selected_spec.length === this.data.part_list.length && this.checkSelected(this.data.selected_spec)) {
        //将两种规格选择都置为可选
        this.data.part_list.forEach(item => {
          item.list.forEach(_item => {
            _item.is_allow = 1;
          })
        })
        //根据所选规格确定具体商品
        this.data.specDetail.forEach(item => {
          let bool = true;
          for (let key in item) {
            if (/spec\d/.test(key)) {
              if (!this.data.selected_spec.includes(item[key])) {
                bool = bool && false
              }
            }
          }
          if (bool) {
            amount = item.amount;
            price = item.platform_price;
            part = item;
            allowBuy = true;
          }
        })
      } else {
        for (let i in this.data.part_list) {
          if (i == p_index) continue;
          this.data.part_list[i].list.forEach(item => {
            item.is_allow = allow.includes(item.name) ? 1 : 0
          });
        }
        amount = this.data.amount;
        price = this.data.data.zk_price;
        part = {}
      }
      this.setData({
        part_list: this.data.part_list,
        amount: amount,
        price: price,
        selected_part: part,
        allowBuy: allowBuy
      })
    })

  },
  checkSelected(selected) {
    let res = true;
    selected.forEach(item => {
      if (!item) res = res && false
    })
    return res
  },
  closePart() {
    this.setData({
      show_part: false,
	  flex_center:false
    })
  },
  async goBuy(e) { //星品 购买 操作
  
 //    if(!allowBuy){
	// 	wx.showToast({
	// 		title:"请选择商品信息",
	// 		icon: 'loading',
	// 		duration: 500,
	// 	});
	// 	return;
	// }

    let path = `/pages/module/commitOrder/commitOrder?room_id=${this.data.options.room_id}&spec_id=${this.data.selected_part.id}&custom_params=${this.data.fromOptions.custom_params}&sub_pid=`

    // 生成渠道 ;自购的 渠道就是自己
    if (this.data.options && this.data.options.openid != undefined && this.data.options.openid != '') {

      let userInfo = app.globalData.userInfo
      wx.showLoading({
        title: '提交中...',
      })
      let sub_uid = await getuid_byopenid({ open_id: this.data.options.openid })
      if (sub_uid != "") {

        let param = `room_id=${this.data.options.room_id}&spec_id=${this.data.selected_part.id}`
        const { data } = await convert({

          p: this.data.data.p,
          content: param, //商品id
          uid: sub_uid.data,
          buyer_uid: userInfo.uid
        })
        /*
        wx.navigateTo({
          url: data.wxapp_page_path,
        })*/
        path = data.wxapp_page_path
        console.log('====XP convert link path:',path)

        wx.hideLoading({
          success: (res) => {},
        })
      }

    }

    console.log('=====order path: ', path)
    const allow = this.data.allowBuy;
    if (!allow) {
		wx.showToast({
		  title: '请选择规格',
		  icon: 'none',
		  duration: 1500
		})
		return;
	}
	
    const data = JSON.parse(JSON.stringify(this.data.data))
    const part = JSON.parse(JSON.stringify(this.data.selected_spec))
    data.count = this.data.part_count;
    data.part = part;
    data.price = this.data.selected_part.market_price;
    data.zk_price = this.data.selected_part.platform_price;
    data.amount = this.data.amount;
    app.globalData.cur_product_buy = data;
    wx.navigateTo({
      //url: '/pages/module/commitOrder/commitOrder',
      url: path
    })
  },
  goBuy1(e) {
	 // let path = `/packageTab/pages/commitOrder/commitOrder?room_id=${this.data.options.room_id}&spec_id=${this.data.selected_part.id}&custom_params=${this.data.fromOptions.custom_params}&sub_pid=`
	  
	     
	  // 生成渠道 ;自购的 渠道就是自己
	  // if (this.data.options && this.data.options.openid != undefined && this.data.options.openid != '') {
	  
	  //   let userInfo = app.globalData.userInfo
	  //   wx.showLoading({
	  //     title: '提交中...',
	  //   })
	  //   let sub_uid = await getuid_byopenid({ open_id: this.data.options.openid })
	  //   if (sub_uid != "") {
	  
	  //     let param = `room_id=${this.data.options.room_id}&spec_id=${this.data.selected_part.id}`
	  //     const { data } = await convert({
	  
	  //       p: this.data.data.p,
	  //       content: param, //商品id
	  //       uid: sub_uid.data,
	  //       buyer_uid: userInfo.uid
	  //     })

	  //     path = data.wxapp_page_path
	  //     console.log('====XP convert link path:',path)
	  
	  //     wx.hideLoading({
	  //       success: (res) => {},
	  //     })
	  //   }
	  
	  // }
	  const allow = this.data.allowBuy;
	  if (!allow) {
	  wx.showToast({
	    title: '请选择规格',
	    icon: 'none',
	    duration: 1500
	  })
	  return;
	  }
	  const data = JSON.parse(JSON.stringify(this.data.data))
	  const part = JSON.parse(JSON.stringify(this.data.selected_spec))
	  data.count1 = this.data.part_count;
	  data.count2 = this.data.part_count1; //劵
	  data.part = part;
	  data.price = this.data.selected_part.market_price;
	  data.zk_price = this.data.selected_part.platform_price;
	  data.amount = this.data.amount;
	  app.globalData.cur_product_buy = data;

	  wx.navigateTo({
	    url:`/packageTab/pages/commitOrder/commitOrder?room_id=${this.data.options.room_id}&spec_id=${this.data.selected_part.id}&custom_params=${this.data.fromOptions.custom_params}&sub_pid=`
	  })
  },
  handleDownload(e) {
      let link = e.currentTarget.dataset.link;
	  console.log(link);
      let fileName = new Date().valueOf();
	 // console.log(wx.env.USER_DATA_PATH + '/' + fileName + '.mp4');
          wx.showLoading({
            title: '视频下载中...',
          })
      wx.downloadFile({
        url: link,
       // filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4',
        success: res => {
          console.log(res);

          let filePath = res.tempFilePath;
          wx.saveVideoToPhotosAlbum({
            filePath,
            success: file => {
              wx.showToast({
                title: '下载成功',
                icon: 'success',
                duration: 2000
              })

  //             wx.hideLoading({
  //               success: (res) => {},
  //             })

  //             let fileMgr = wx.getFileSystemManager();
  //             fileMgr.unlink({
  //               filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4',
  //               success: function (r) {
  
  //               },
  //             })
            },
            fail: err => {
              console.log(err)
              wx.showToast({
                title: '下载失败',
                icon: 'success',
                duration: 2000
              })
              // wx.hideLoading({
              //   success: (res) => {},
              // })

              if (err.errMsg === 'saveVideoToPhotosAlbum:fail auth deny') {
                wx.showModal({
                  title: '提示',
                  content: '需要您授权保存相册',
                  showCancel: false,
                  success: data => {
                    wx.openSetting({
                      success(settingdata) {
                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          wx.showModal({
                            title: '提示',
                            content: '获取权限成功,再次点击下载即可保存',
                            showCancel: false,
                          })
                        } else {
                          wx.showModal({
                            title: '提示',
                            content: '获取权限失败，将无法保存到相册哦~',
                            showCancel: false,
                          })
                        }
                      },
                    })
                  }
                })
              }
            }
          })
        }
      })
    },
  downloadImg1: function (e) {　　　　　　　　　　　　　　　　//触发函数
  
    var imgSrc=e.currentTarget.dataset.src.slice(23);
    var save = wx.getFileSystemManager();
    var number = Math.random();
	console.log(imgSrc);
    save.writeFile({
        filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',　　　　　　　//需要下载的图片url
	    data: imgSrc,
	    encoding: 'base64',
      success: function (res) {　　　　　　　　　　//成功后的回调函数
	    console.log(res);
        wx.saveImageToPhotosAlbum({　　　　　　　　　//保存到本地
          filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
          success(res) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail: function (err) {
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                  }
                }
              })
            }
          }
       })
      },fail:err=>{
		  console.log(err);
	  }
    });
 
 
		 
  },
  touchmove() {
    return;
  },
  lookImg(e) {
    var image_url = e.currentTarget.dataset.image_url;
    wx.previewImage({
      current: image_url,
      urls: [image_url],
    })
  },

  more() {
    this.setData({
      showMore: !this.data.showMore
    })
  },
  goTop() {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  startPlay() {
    this.setData({
      iconShow: 0
    })
  },
  select(e) {
    var select_list = this.data.new_arr;
    select_list[e.currentTarget.dataset.index].select = !select_list[e.currentTarget.dataset.index].select
    this.setData({
      new_arr: select_list
    })
  },
  downloadImg() {  // 保存海报
    this.downImg()
  },
  downImg() {
	 // console.log("保存");
    let that = this
    let down_num = 0;
    var select_list = []
    if (this.data.btnArr[this.data.cur_btn_index].id == 1) { //update by finder
      select_list = [{ src: this.data.downImg }]
    } else {
      //select_list = this.data.select_list
      for (var i = 0; i < this.data.select_list.length; i++) {
        if (this.data.select_list[i].select == 1 && this.data.select_list[i].imgShow) {
          select_list[select_list.length] = this.data.select_list[i]
        }

      }

    }
 //    console.log(this.data.btnArr[this.data.cur_btn_index].id);
	 console.log(this.data.select_list);
    console.log("等待下载图片")
    wx.showLoading({
      title: '正在保存图片',
    })

    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.savePhoto(select_list, down_num);
            },
            fail() {
              wx.openSetting({
                success() {
                  wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() {
                      that.savePhoto(select_list, down_num);
                    }
                  })
                }
              })
            }
          })
        } else {
          that.savePhoto(select_list, down_num)
        }
      }
    })
  },//
  async savePhoto(select_list, down_num) {
    let that = this
	//console.log(select_list, down_num);
    var _select_list = select_list
    var image_url = _select_list[down_num].src

    wx.showLoading({
      title: '正在保存第'+ (down_num+1) +'张图片',
    })

    

    if (_select_list[down_num].select != true) {
      down_num++
      if (down_num == 9) {

        wx.hideLoading({
          success: (res) => { },
        })

        wx.showToast({
          title: '保存成功',
          icon: "success",
          duration: 1000
        })

        return
      } else {
        that.savePhoto(_select_list, down_num);
      }
    }
 
    if(image_url.startsWith('http://tmp')){ //解决 二维码 http://tmp 本地存储问题,之前是本地处理的二维码
    
      image_url= text2qr({text:this.data.zhuan_url})
    }else{

      // 1. 根据 image_url 先判断是否在 已配置的下载域名中
      if(app.is_in_downloadUrls(image_url)){
        // image_url 就不做任何修改
        console.log('===支持的下载链接',image_url)
      }else{
        log.info('==图片上传 没有包含就上传我们服务器转 '+image_url)
        // 没有包含就上传我们服务器转 
        let { data } = await upload_starx_singletmp({ url: image_url })
        image_url = data
        if (!image_url.startsWith('http')) {
          image_url = 'https:' + image_url
        }
      }

    }
    
   

    wx.downloadFile({
      url: image_url,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            down_num++
            if (down_num == _select_list.length || down_num == 9) {

              wx.hideLoading({
                success: (res) => { },
              })

              wx.showToast({
                title: '保存成功',
                icon: "success",
                duration: 1000
              })
            } else {
              that.savePhoto(_select_list, down_num);
            }
          }
        })
      }
    })
  }, //
  async favorite() {
    const { data } = await collect({
      uid: app.globalData.uid,

    })
  },
  swiperChange(e) {
    if (this.data.data.small_images[0] && e.detail.current != 0) {
      this._videoContext = wx.createVideoContext('video');
      this._videoContext.pause();
    } else if (this.data.data.small_images[0] && e.detail.current == 0) {
      this._videoContext.play();
    }
    this.setData({
      currentIndicator: e.detail.current + 1
    })
  },
  stopPro() {
    return
  },
  onTabClick(e) {
    console.log('tab点击', e.currentTarget.dataset)
    var id = e.currentTarget.dataset.index;
    this.setData({
      cur_btn_index: id
    })


    if(id==2){
      // 显示多图
      if (this.data.new_arr.length <= 6) {
        // this.data.new_arr[1] = { src: e.detail.qrcode_img, select: 1 }
          this.data.new_arr[1] = {src:this.data.qrcode_img,select:1,imgShow:true,path:this.data.qrcode_img}
       } else {
        // this.data.new_arr[4] = { src: e.detail.qrcode_img, select: 1 }
          this.data.new_arr[4] = {src:this.data.qrcode_img,select:1,imgShow:true,path:this.data.qrcode_img}
       }
       this.setData({
         new_arr: this.data.new_arr
       })
   
    }
  },
  showTghb() {
    this.setData({
      show_tghb: true
    })
  },
  onTabClick1(e) {
    var that = this
    var index = e.detail.index;
    if (index == 0) {
      this.showDetail();
    }
    wx.pageScrollTo({
      scrollTop: index == 1 ? this.data.image_box_top : this.data.menuTop
    })
  },

  copy(e) {
    var that = this;
    var cont = e.currentTarget.dataset.cont;
    wx.setClipboardData({
      data: cont,
      success() {
        wx.showToast({
          title: '复制成功'
        })
        setTimeout(() => {
          that.setData({
            is_show_big1: 0,
            is_show_big: 0
          })
        }, 1000);
      },
    })
  },
  productDetail(e) {
    var id = e.currentTarget.dataset.id;
    wx.redirectTo({
      url: '/pages/module/productDetail/productDetail?id=' + id,
    })
  },
  closeDown1() {
    this.setData({
      show_load: false
    })
  },
  imgLoad(e) {
    var index = e.currentTarget.dataset.index;
    this.data.main_images[index].imgShow = true;
    this.setData({
      main_images: this.data.main_images
    })
  },
  handleXpShare(e) {
    console.log(this.data.fromOptions);
    this.handleXpHide();
    wx.navigateTo({
      url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${this.data.fromOptions.room_id}&custom_params=${this.data.fromOptions.custom_params}`
    })
  },
  handleXpHide() {
    this.setData({
      show_share_xp: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    wx.createSelectorQuery().select(".video_box").boundingClientRect((res) => {
      that.destination = res;
    }).exec();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    this.handleXpHide();
    if (!this.data.is_login_back) return
   // await this.showDetail()  这里为什么还需要加
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: async function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: async function () {
    var that = this;
	console.log('是这个');
    // if (!this.canLoadMore) return;
    // wx.showLoading({
    //   title: this.page == 1 ? '加载中...' : '加载更多...',
    // });
    // let {data} = await search({q:this.data.data.cid_name || '',p: '',page_index:this.page+1,page_size:8})
    // let arr = data;
    // if (arr.length > 0) {
    //     this.page++;
    //     this.setData({
    //       productList:[...this.data.productList, ...arr],
    //     })
    // } else {
    //     this.canLoadMore = false;
    // }
    wx.hideLoading();
  },

  // onUnload: function () {
  //   if (getApp().globalData.toIndexFlag) {
  //     wx.reLaunch({
  //       url: index
  //     })
  //     getApp().globalData.toIndexFlag = false;
  //   }

  // },


  onShareAppMessage: function (options) {
	  // console.log("分享")
	 
    if (!app.is_auth()){
      wx.showToast({
        title: '请先登陆后，才能分享',
      })
      // 请先登陆
      wx.navigateTo({
        url: '/pages/login/login?' + jsonParamToQueryStr(this.data.options),
      })
      return 
    }
    
    if (options.from=='button'){
      console.log('按钮分享:',options.target)
    }else {

      // 上方分享
      console.log('上方分享')
    }

	  // 商品分享的 scene=100
	var path='/pages/module/productDetail/productDetail?id=' + this.data.data.item_id + '&p=' + this.data.data.p + '&scene=10001&share_uid=' + app.globalData.userInfo.uid
	console.log('share open path: ',path); 
	
    //recordGrowth({ tasktype: 4 })

    
    // if(this.data.data.video_info_high.play_url && this.data.data.p=='JD'){
    //   goods_item_save(this.data.data)  
    // }
   

    // if(!this.data.share_title){
    //   let title='原价:'+this.data.data.price+'元, 券后价:'+this.data.data.qh_price+'元-抢爆了,好物得分享哦-'+this.data.data.title
    //   this.setData({
    //     share_title:title
    //   })
    // }
    return {
      imageUrl: this.data.data.pict_main_url,
      path: path,
      title: this.data.level_1,
    }
  },
  onShareTimeline() {//监听右上角菜单“分享到朋友圈”按钮的行为

    // 自定义页面路径中携带的参数，如 path?a=1&b=2 的 “?” 后面部分
    var q='id=' + this.data.data.item_id + '&p=' + this.data.data.p + '&scene=10001&share_uid=' + app.globalData.userInfo.uid
    recordGrowth({ tasktype: 4 })

    if(!this.data.share_title){
      let title='原价:'+this.data.data.price+'元, 券后价:'+this.data.data.qh_price+'元-限购一件-'+this.data.data.title
      this.setData({
        share_title:title
      })
    }

    // if(this.data.data.video_info_high.play_url && this.data.data.p=='JD'){
    //   goods_item_save(this.data.data)  
    // }

    log.info('==== 朋友圈分享 q:'+q+',share_title:'+this.data.share_title)
    return {
      imageUrl: this.data.data.pict_main_url,
      query: q,
      title: this.data.level_1,
    }
  }
})